<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>

        <span>|</span>

        <span>添加角色</span>
      </div>

      <div class="right">黑马程序员</div>
    </header>

    <main class="add-main">
      <div class="step-container">
        <!-- 步骤条组件 -->
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>

      <!-- 三个div对应步骤的内容 -->
      <div v-show="activeStep === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form class="form-box" ref="roleForm" :model="roleForm" :rules="roleRules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>

            <el-form-item label="角色描述">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>

      </div>

      <div v-show="activeStep === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>

              <el-tree ref="tree" :data="item.children" show-checkbox default-expand-all node-key="id" highlight-current
                :props="{ label: 'title' }" check-strictly />
            </div>
          </div>
        </div>

      </div>

      <div v-show="activeStep === 3" class="form-container">
        <div class="title">检查并完成</div>

        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>

            <div class="form-item">角色描述：{{ roleForm.remark }}</div>

            <div class="form-item">角色权限：</div>

            <div class="tree-wrapper">
              <div v-for="item in disableTreeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>

                <el-tree ref="diabledTree" :data="item.children" show-checkbox default-expand-all node-key="id"
                  :highlight-current="false" :props="{ label: 'title' }" check-strictly />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-show="activeStep > 1" @click="decreseStep">上一步</el-button>

        <el-button v-show="activeStep < 3" type="primary" @click="increseStep">下一步</el-button>
        <el-button v-show="activeStep === 3" type="primary" @click="confirmAdd">确认提交</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getTreeListAPI, createRoleUserAPI } from "@/api/permiss";
// 定义递归函数实现数据属性的动态添加
function addDisabled(datas) {
  // 1. 遍历datas这个数组中的对象，动态添加Disabled：true
  /*
  data:{ id:1,title:'',children:[] }
  data:{ id:1,title:''}
  */
  datas.forEach((data) => {
    data.disabled = true;

    // 判断data对象中如果有children，则继续调用 addDisabled(data.children) 给下一层继续添加 disabled = true;
    if (data.children) {
      addDisabled(data.children);
    }
  });
}
export default {
  data() {
    return {
      activeStep: 1,
      treeList: [],// 权限树形列表
      disableTreeList: [], //显示第三步的回显数据树基础数据,来源于treeList的深拷贝
      roleForm: {
        roleName: "",
        remark: "",
        perms: [], //权限点的二维数组
      },
      roleRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    // 在初始化时候就加载好
    this.getTreeList()
  },
  methods: {
    // 将数据提交给服务器完成角色添加功能
    async confirmAdd() {
      // 1. 调用api/方法和服务器通讯
      await createRoleUserAPI(this.roleForm);

      // 2. 提示用户添加成功
      this.$message.success("添加成功");
      this.$router.push("/sys/role");
    },
    // 获取功能权限列表
    async getTreeList() {
      const res = await getTreeListAPI()
      this.treeList = res.data

      // 针对res.data做一次深拷贝赋值给disableTreeList
      this.disableTreeList = JSON.parse(JSON.stringify(res.data));
      addDisabled(this.disableTreeList); //递归将数组中的每个对象都添加上 disabled:true
    },
    decreseStep() {
      // 上一步
      this.activeStep--;
      if (this.activeStep < 1) {
        this.activeStep = 1;
      }
    },
    increseStep() {
      // 下一步控制
      //   如果activeStep为2的时候，需要获取树形列表数据
      if (this.activeStep === 2) {
        // this.$message.success("dsfdsdfs");
        this.roleForm.perms = [];
        this.$refs.tree.forEach((item) => {
          // const keys = item.getCheckedKeys(); //选择用户勾选的节点对一个的key
          // this.roleForm.perms.push(keys);
          const keys = item.getCheckedKeys(); //选择用户勾选的节点key值
          this.roleForm.perms.push(keys); //[[],[]]
        });

        // 判断如果this.roleForm.perms有权限点数据则可以继续，否则提示用户必须选择一个权限点
        // 使用数组的一个flat()方法将二维数组转化为一维数组
        // console.log(this.roleForm.perms, this.roleForm.perms.flat());
        // return;

        if (this.roleForm.perms.flat().length === 0) {
          this.$message.error("请选择一个权限点");
          return;
        }

        this.activeStep++;
      }
      // 进入最后一步的时候完成树的数据回显
      if (this.activeStep === 3) {
        // 获取树对象
        this.$refs.diabledTree.forEach((treeobj, index) => {
          treeobj.setCheckedKeys(this.roleForm.perms[index]);
        });
      }
      if (this.activeStep === 1) {
        // 验证表单合法性
        this.$refs.roleForm.validate((valid) => {
          if (valid) {
            this.activeStep++;
          }
        });
      }
      if (this.activeStep > 3) {
        this.activeStep = 3;
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-tree-node__label {
  color: rgba(0, 0, 0, 0.3);
}

// 权限树选择高亮样式复写
::v-deep .el-tree-node__content label.el-checkbox.is-checked {
  span.is-checked .el-checkbox__inner {
    background-color: #0094ff;
  }
}

.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>
